package com.zf.shuashua.ui.mine;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.meis.base.mei.utils.SoftKeyboardUtils;
import com.mob.secverify.CustomUIRegister;
import com.mob.secverify.GetTokenCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.datatype.VerifyResult;
import com.mob.secverify.exception.VerifyException;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.BR;
import com.zf.shuashua.bean.LoginBean;
import com.zf.shuashua.helper.LoadDialogManager;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.R;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BasicActivity;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.OtherLoginBean;
import com.zf.shuashua.databinding.ActivityLoginBinding;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.utils.CustomizeUtils;
import com.zf.shuashua.utils.TextUtil;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.viewmodel.LoginViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.zf.shuashua.MainActivity.isPreVerifyDone;


public class LoginActivity extends BasicActivity<ActivityLoginBinding, LoginViewModel> {
    private String phoneNUmber;
    private String type;
    private String nick_name;
    private String avatar;
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            String open_id = data.get("uid");
            if (open_id == null) {
                open_id = "";
            }
            nick_name = data.get("name");
            if (nick_name == null) {
                nick_name = "";
            }
            avatar = data.get("iconurl");
            if (avatar == null) {
                avatar = "";
            }
            String sex = data.get("gender");
            if (sex == null) {
                sex = "";
            }
            String city = data.get("city");
            if (city == null) {
                city = "";
            }


            if (SHARE_MEDIA.QQ == platform) {
                type = "qq";
            } else if (SHARE_MEDIA.SINA == platform) {
                type = "weibo";
            } else if (SHARE_MEDIA.WEIXIN == platform) {
                if (isActivityEnable()) {
                    LoadDialogManager.getInstance().show(LoginActivity.this);
                }
                type = "wechat";
                open_id = data.get("openid");
                if (open_id == null) {
                    open_id = "";
                }
            }
            HttpData.getInstance().thirdLogin(type, open_id, nick_name, avatar, sex, city, "", "", "", "", new ACallback<BaseData<OtherLoginBean>>() {
                @Override
                public void onSuccess(BaseData<OtherLoginBean> data) {
                    LoadDialogManager.getInstance().dismiss();
                    if (data != null && data.getData() != null) {
                        OtherLoginBean wbLoginBean = data.getData();
                        if (!TextUtils.isEmpty(wbLoginBean.getOpen_id()) && TextUtils.isEmpty(wbLoginBean.getAccess_token())) {
                            Store.getInstance().setOpenId(data.getData().getOpen_id());
                            Store.getInstance().setType(type);
                            jumpToThirdLogin(type, nick_name, avatar);
                        } else {
                            Store.getInstance().loginSuccess(LoginActivity.this, data.getData().getToken_type(), data.getData().getAccess_token(), type);
                            finish();
                        }
                    } else {
                        ToastUtil.showToast(LoginActivity.this, "登录失败,请重试");
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                    LoadDialogManager.getInstance().dismiss();
                }
            });
        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(LoginActivity.this, "登录失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            LoadDialogManager.getInstance().dismiss();
            Toast.makeText(LoginActivity.this, "登录取消了", Toast.LENGTH_LONG).show();
        }
    };

    public boolean isActivityEnable() {
        if (isDestroyed() || isFinishing()) {
            return false;
        }
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public int getViewModelId() {
        return BR.viewModel;
    }

    @Override
    public LoginViewModel getViewModel() {
        return ViewModelProviders.of(this).get(LoginViewModel.class);
    }

    @Override
    public void setupView() {
        binding.imgBack.setOnClickListener(v -> {
            reportAdvertAction(TrackConstants.ACTION_LOGIN_RETURN, TrackConstants.NOTE_LOGIN_RETURN);
            finish();
        });
        binding.tvtoProtocol.setOnClickListener(v -> {
            jumpToProtocol();
        });
        binding.tvtoPolicy.setOnClickListener(v -> {
            jumpToPolicy();
        });
        binding.tvNext.setOnClickListener(v -> {
            if (binding.cbAgree.isChecked()) {
                reportAdvertAction(TrackConstants.ACTION_LOGIN_SUBMIT, TrackConstants.NOTE_LOGIN_SUBMIT);
                jumpToCode();
            } else {
                ToastUtil.showToast(this, "需先同意长豆用户协议和隐私政策");
            }
        });
        if (getIntent().getStringExtra("action") == null && isPreVerifyDone && SecVerify.isVerifySupport()) {
            addCustomView();
            customizeUi();
        }
        setupPhone();
        setupWeixinLogin();
        setupWeiboLogin();
        setupQQLogin();
    }

    private void customizeUi() {
        SecVerify.setUiSettings(CustomizeUtils.customizeUi());
        //是否自动关闭授权页面
        SecVerify.autoFinishOAuthPage(true);
        verify();

    }

    private void addCustomView() {
        View view = LayoutInflater.from(this).inflate(R.layout.shanyan_demo_other_login_item, null);
        RelativeLayout.LayoutParams layoutParamsOther = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        layoutParamsOther.addRule(RelativeLayout.CENTER_HORIZONTAL);
        view.setLayoutParams(layoutParamsOther);
        otherLogin(view);
        List<View> views = new ArrayList<>();
        views.add(view);
        CustomUIRegister.addCustomizedUi(views, view1 -> {
        });
    }

    private void otherLogin(View relativeLayout) {
        LinearLayout weixin_login = relativeLayout.findViewById(R.id.weixin_login);
        LinearLayout weibo_login = relativeLayout.findViewById(R.id.weibo_login);
        LinearLayout qq_login = relativeLayout.findViewById(R.id.qq_login);
        TextView tvPhone = relativeLayout.findViewById(R.id.tvPhone);
        weixin_login.setOnClickListener(view -> {
            //关闭授权页
            SecVerify.finishOAuthPage();
            reportAdvertAction(TrackConstants.ACTION_LOGIN_WECHAT, TrackConstants.NOTE_LOGIN_WECHAT);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.WEIXIN)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
//                            LoadDialogManager.getInstance().show(LoginActivity.this);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
            }
        });
        weibo_login.setOnClickListener(view -> {
            //关闭授权页
            SecVerify.finishOAuthPage();
            reportAdvertAction(TrackConstants.ACTION_LOGIN_BLOG, TrackConstants.NOTE_LOGIN_BLOG);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.SINA)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
                LoadDialogManager.getInstance().show(LoginActivity.this);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安装微博客户端", Toast.LENGTH_SHORT).show();
            }
        });
        qq_login.setOnClickListener(view -> {
            //关闭授权页
            SecVerify.finishOAuthPage();
            reportAdvertAction(TrackConstants.ACTION_LOGIN_QQ, TrackConstants.NOTE_LOGIN_QQ);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.QQ)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                LoadDialogManager.getInstance().show(LoginActivity.this);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安QQ客户端", Toast.LENGTH_SHORT).show();
            }
        });

        tvPhone.setOnClickListener(view -> {
            //关闭授权页
            SecVerify.finishOAuthPage();
        });
    }

    /**
     * 免密登录
     */
    private void verify() {
//        CommonProgressDialog.showProgressDialog(this);
        //需要在verify之前设置
        SecVerify.verify((code, desc) -> {
            // 授权页面相关回调及错误码
            if (code != 6119140) {
//                CommonProgressDialog.dismissProgressDialog();
            }

        }, new GetTokenCallback() {
            @Override
            public void onComplete(VerifyResult data) {
                HttpData.getInstance().oneLogin(data.getToken(), data.getOpToken(), data.getOperator(), new ACallback<LoginBean>() {
                    @Override
                    public void onSuccess(LoginBean data) {
//                        CommonProgressDialog.dismissProgressDialog();
                        if (data != null) {
                            if (data.getCode() == 200) {
                                Store.getInstance().setIsNewUser(data.getData().isIs_new_user());//新人
                                Store.getInstance().loginSuccess(LoginActivity.this, data.getData().getToken_type(), data.getData().getAccess_token(), data.getData(), "ZH");
                                finish();
                            } else {
                                ToastUtil.showToast(LoginActivity.this, "一键登录失败,请用其他方式登录。");
                            }
                        } else {
                            ToastUtil.showToast(LoginActivity.this, "一键登录失败,请用其他方式登录。");
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
//                        CommonProgressDialog.dismissProgressDialog();
                        ToastUtil.showToast(LoginActivity.this, "服务器异常,请用其他方式登录。");
                    }
                });

            }

            @Override
            public void onFailure(VerifyException e) {
//                CommonProgressDialog.dismissProgressDialog();
            }
        });

    }

    private void reportAdvertAction(String action, String note) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_LOGIN, action, note);
    }

    @Override
    public void initData() {
        super.initData();
        String action = getIntent().getStringExtra("action");
        if ("logout".equals(action)) {
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }
    }

    private void setupPhone() {
        binding.phoneNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s) && TextUtil.isMobile(s.toString())) {
                    binding.tvNext.setEnabled(true);
                    phoneNUmber = s.toString();
                    SoftKeyboardUtils.closeSoftKeyboard(LoginActivity.this);//隐藏键盘

                } else {
                    binding.tvNext.setEnabled(false);
                    phoneNUmber = "";
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private void setupWeixinLogin() {
        binding.weixinLogin.setOnClickListener(v -> {
            if (!binding.cbAgree.isChecked()) {
                ToastUtil.showToast(this, "需先同意长豆用户协议和隐私政策");
                return;
            }
            reportAdvertAction(TrackConstants.ACTION_LOGIN_WECHAT, TrackConstants.NOTE_LOGIN_WECHAT);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.WEIXIN)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安装微信客户端", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupWeiboLogin() {
        binding.weiboLogin.setOnClickListener(v -> {
            if (!binding.cbAgree.isChecked()) {
                ToastUtil.showToast(this, "需先同意长豆用户协议和隐私政策");
                return;
            }
            reportAdvertAction(TrackConstants.ACTION_LOGIN_BLOG, TrackConstants.NOTE_LOGIN_BLOG);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.SINA)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
                LoadDialogManager.getInstance().show(LoginActivity.this);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安装微博客户端", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupQQLogin() {
        binding.qqLogin.setOnClickListener(v -> {
            if (!binding.cbAgree.isChecked()) {
                ToastUtil.showToast(this, "需先同意长豆用户协议和隐私政策");
                return;
            }
            reportAdvertAction(TrackConstants.ACTION_LOGIN_QQ, TrackConstants.NOTE_LOGIN_QQ);
            UMShareConfig config = new UMShareConfig();
            config.isNeedAuthOnGetUserInfo(true);
            UMShareAPI.get(LoginActivity.this).setShareConfig(config);
            if (UMShareAPI.get(LoginActivity.this).isInstall(LoginActivity.this, SHARE_MEDIA.QQ)) {
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                LoadDialogManager.getInstance().show(LoginActivity.this);
            } else {
                Toast.makeText(LoginActivity.this, "您的设备未安QQ客户端", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void jumpToProtocol() {
        Intent intent = new Intent(this, H5Activity.class);
        intent.putExtra("money", Constants.H5_URL + "protocol");
        intent.putExtra("title", "长豆用户协议");
        startActivity(intent);
    }

    private void jumpToPolicy() {
        Intent intent = new Intent(this, H5Activity.class);
        intent.putExtra("money", Constants.H5_URL + "policy");
        intent.putExtra("title", "长豆隐私政策");
        startActivity(intent);
    }

    private void jumpToCode() {
        if (TextUtil.isMobile(phoneNUmber)) {
            Intent intent = new Intent(this, VerifyActivity.class);
            intent.putExtra("phoneNumber", phoneNUmber);
            startActivity(intent);
        }
    }

    private void jumpToThirdLogin(String type, String name, String iconUrl) {
        Intent intent = new Intent(this, BindPhoneActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("name", name);
        intent.putExtra("iconUrl", iconUrl);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(LoginActivity.this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        LoadDialogManager.getInstance().dismiss();
        UMShareAPI.get(this).release();
        super.onDestroy();
    }
}
